import 'package:cbec_app/components/base/base_chekbox.dart';
import 'package:cbec_app/components/base/base_interactive.dart';
import 'package:cbec_app/components/base/base_page.dart';
import 'package:cbec_app/components/common/common_style.dart';
import 'package:cbec_app/components/common/consignee_info.dart';
import 'package:cbec_app/components/common/detail_item.dart';
import 'package:cbec_app/components/base/base_nav_bar.dart';
import 'package:cbec_app/components/goods/goods_info_item.dart';
import 'package:cbec_app/components/popup/coupon_popup.dart';
import 'package:cbec_app/components/popup/redpack_popup.dart';
import 'package:cbec_app/pages/goods/controller/fill_order_ctr.dart';
import 'package:cbec_app/pages/my/controller/statement_ctr.dart';
import 'package:cbec_app/routes/routes.dart';
import 'package:cbec_app/utils/ThemeConfig.dart';
import 'package:cbec_app/utils/Tools.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';

///填写订单页
class FillOrderPage extends GetView<FillOrderController> {
  const FillOrderPage({super.key});

  @override
  Widget build(BuildContext context) {
    return GetBuilder<FillOrderController>(
      builder: (controller) {
        return BasePage(
          iconType: IconType.back,
          bgColor: ThemeConfig.bodyColor,
          isShowPadding: true,
          isIconTitle: true,
          paddingTop: 10.h,
          title: '填写订单',
          children: [
            if (controller.commodityForm == 2) ...[
              ///购买的商品
              _commonBox(ClipRRect(
                borderRadius: BorderRadius.all(Radius.circular(8.h)),
                child: Column(
                    children: controller.goodsList
                        .map((item) => GoodsInfoItem(
                              goodsInfo: item,
                              infoStyle: InfoStyle.fillOrder,
                              isCanSelect: false,
                              isShowGoodsNum: true,
                              // btnType: RightBtnType.addMinus,
                            ))
                        .toList()),
              )),

              _commonBox(Column(
                children: [
                  const SizedBox(height: 10),
                  // 积分
                  DetailItem(
                    label: '积分（共${controller.pointsInfo['hasPoints'].toString()}分）',
                    content: controller.showPointsPrice,
                    contentStyle: (controller.pointsInfo.isNotEmpty && controller.pointsInfo['hasPoints'] > 0) ? ContentStyle.nextMore : ContentStyle.normal,
                    contentColor: '#e97466',
                    onTap: () {
                      controller.selectPointsPay();
                    },
                  ),
                  // 预付卡
                  DetailItem(
                    label: '预付卡（余额：${controller.payCardInfo['hasBdPayCardBalance'].toString()}元）',
                    content: controller.showCardPrice,
                    contentStyle: (controller.payCardInfo.isNotEmpty && controller.payCardInfo['hasBdPayCardBalance'] > 0) ? ContentStyle.nextMore : ContentStyle.normal,
                    contentColor: '#e97466',
                    onTap: () {
                      controller.selectCardPay();
                    },
                  ),

                  const SizedBox(height: 10),
                ],
              )),

              _commonBox(Container(
                padding: const EdgeInsets.all(8),
                height: 40,
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: [
                    Text(
                      '配送',
                      style: TextStyle(color: Tools.fromHex('#a4a4a4')),
                    ),
                    Text(
                      '付款后自动发放至账户',
                      style: TextStyle(color: Tools.fromHex('#a4a4a4')),
                    ),
                  ],
                ),
              )),
            ] else ...[
              ConsigneeInfo(
                receiveName: controller.addressInfo?['receiveName'] ?? '',
                receiveMobile: controller.addressInfo?['receivePhone'] ?? '',
                receiveAddress: '${controller.addressInfo?['provinceName']}${controller.addressInfo?['cityName']}${controller.addressInfo?['districtName']}',
                receiveInfo: controller.addressInfo?['receiveAddress'] ?? '',
                isDefault: controller.addressInfo?['isDefault'] == 1 ? true : false,
                btnType: EditBtnType.select,
                alignment: CrossAxisAlignment.center,
              ),

              ///购买的商品
              _commonBox(ClipRRect(
                borderRadius: BorderRadius.all(Radius.circular(8.h)),
                child: Column(
                    children: controller.goodsList
                        .map((item) => GoodsInfoItem(
                              goodsInfo: item,
                              infoStyle: InfoStyle.fillOrder,
                              isCanSelect: false,
                              isShowGoodsNum: true,
                              // btnType: RightBtnType.addMinus,
                            ))
                        .toList()),
              )),
              _commonBox(ClipRRect(
                borderRadius: BorderRadius.all(Radius.circular(8.h)),
                child: Column(
                  children: [
                    //定金预售
                    controller.detail['presaleType'] == 2
                        ? DetailItem(
                            label: '阶段1：定金',
                            contentStyle: ContentStyle.title,
                            content: '￥${controller.deposit}',
                          )
                        : emptyWidget(),
                    controller.detail['presaleType'] == 2
                        ? DetailItem(
                            label: '阶段2：尾款',
                            contentStyle: ContentStyle.title,
                            content: '￥${controller.detail['finalPay'].toString()}',
                          )
                        : emptyWidget(),
                    controller.detail['presaleType'] == 2
                        ? Padding(
                            padding: EdgeInsets.only(top: 10, bottom: 10, right: 10.w),
                            child: Row(
                              mainAxisAlignment: MainAxisAlignment.end,
                              children: [
                                Text('${controller.detail['presaleStartTime']}可支付，若有优惠可叠加',
                                    style: setTextStyle(
                                      13,
                                      FontWeight.w500,
                                      Color(0xff3d3d3d),
                                    ))
                              ],
                            ),
                          )
                        : emptyWidget(),
                    //全款预售
                    controller.detail['presaleType'] == 1
                        ? DetailItem(
                            label: '全款',
                            contentStyle: ContentStyle.title,
                            content: '￥${controller.detail['priceTotal'].toString()}',
                          )
                        : emptyWidget(),
                    controller.detail['presaleType'] == 1
                        ? Padding(
                            padding: EdgeInsets.only(top: 10, bottom: 10, right: 10.w),
                            child: Row(
                              mainAxisAlignment: MainAxisAlignment.end,
                              children: [
                                Text('(该预售商品仅支持全款支付)',
                                    style: setTextStyle(
                                      13,
                                      FontWeight.w500,
                                      Color(0xff3d3d3d),
                                    ))
                              ],
                            ),
                          )
                        : emptyWidget(),
                    //普通商品
                    controller.placeOrderParams['type'] != 5
                        ? DetailItem(
                            label: '商品金额',
                            content: '￥${controller.detail['priceTotal'].toString()}',
                          )
                        : emptyWidget(),
                    // 商品促销
                    getPriceGoodsDiscountStyle(),
                    //会员优惠
                    getVipStyle(),
                    // 整单优惠
                    getFullDiscount(),
                    // 活动优惠
                    getDiscountStyle(),

                    // 砍价不展示优惠券和红包
                    if (controller.placeOrderParams['type'] != 8) ...[
                      // 优惠券
                      getCouponPriceStyle(),
                      // 红包
                      getRedPackPriceStyle(),
                    ],

                    // 运费
                    DetailItem(
                      label: '运费',
                      content: '￥${controller.priceExpress.toString()}',
                    ),

                    // 税费

                    if (controller.showTax)
                      DetailItem(
                        label: '税费',
                        content: '￥${controller.tax.toString()}',
                      ),

                    // 积分
                    DetailItem(
                      label: '积分（共${controller.pointsInfo['hasPoints'].toString()}分）',
                      content: controller.showPointsPrice,
                      contentStyle: (controller.pointsInfo.isNotEmpty && controller.pointsInfo['hasPoints'] > 0) ? ContentStyle.nextMore : ContentStyle.normal,
                      contentColor: '#e97466',
                      onTap: () {
                        controller.selectPointsPay();
                      },
                    ),
                    // 预付卡
                    DetailItem(
                      label: '预付卡（余额：${controller.payCardInfo['hasBdPayCardBalance'].toString()}元）',
                      content: controller.showCardPrice,
                      contentStyle: (controller.payCardInfo.isNotEmpty && controller.payCardInfo['hasBdPayCardBalance'] > 0) ? ContentStyle.nextMore : ContentStyle.normal,
                      contentColor: '#e97466',
                      onTap: () {
                        controller.selectCardPay();
                      },
                    ),

                    const Divider(color: ThemeConfig.divideColor, thickness: 1, height: 10),
                    DetailItem(
                      label: '',
                      content: '小计：￥${controller.actualPrice}',
                    ),

                    emptyMargin(10.h)
                  ],
                ),
              )),

              if ((controller.placeOrderParams['type'] == 5) && (controller.detail['presalePayReturn'] == 0)) ...[
                // presalePayReturn	定金是否支持退款 0-否 1-是
                emptyMargin(10.h),
                depositWidget(),
              ],

              _commonBox(ClipRRect(
                borderRadius: BorderRadius.all(Radius.circular(8.h)),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Container(
                      padding: EdgeInsets.only(left: 10.w, right: 10.w, top: 10.h),
                      child: Text('订单备注', style: setTextStyle(14, FontWeight.w700, ThemeConfig.mainTextColor)),
                    ),
                    Container(
                      margin: EdgeInsets.all(10.w),
                      child: CupertinoTextField(
                        placeholder: '选填，合理需求我们会尽量满足',
                        placeholderStyle: setTextStyle(14, FontWeight.w300, ThemeConfig.subTextColor),
                        style: setTextStyle(14, FontWeight.w300, ThemeConfig.mainTextColor),
                        decoration: const BoxDecoration(border: Border()),
                        maxLines: 5,
                        onChanged: (value) {
                          controller.inputRemark(value);
                        },
                      ),
                    )
                  ],
                ),
              )),
            ],
            emptyMargin(70.h),
            _operateBox(context)
          ],
        );
      },
    );
  }

  ///获取会员优惠样式
  Widget getVipStyle() {
    if (controller.detail['priceVipDiscount'] != null && controller.detail['priceVipDiscount'] > 0) {
      return DetailItem(
        label: '会员优惠',
        labelStyle: LabelStyle.labelTitleRed,
        tagName: '会',
        content: '-￥${controller.detail['priceVipDiscount'].toString()}',
      );
    } else {
      return emptyWidget();
    }
  }

  /// 整单优惠
  Widget getFullDiscount() {
    return Visibility(
      visible: (controller.detail['priceFullDiscount'] != null && controller.detail['priceFullDiscount'] > 0),
      child: DetailItem(
        label: '整单优惠',
        labelStyle: LabelStyle.labelTitleRed,
        tagName: '整',
        content: '-￥${controller.detail['priceFullDiscount'].toString()}',
      ),
    );
  }

  ///商品促销
  Widget getPriceGoodsDiscountStyle() {
    if (controller.priceGoodsDiscount > 0) {
      return DetailItem(
        label: '商品促销',
        labelStyle: LabelStyle.labelTitleYellow,
        tagName: '促',
        content: '-￥${controller.priceGoodsDiscount.toString()}',
      );
    } else {
      return const SizedBox();
    }
  }

  ///活动优惠
  Widget getDiscountStyle() {
    int type = controller.placeOrderParams['type'];
    if (controller.activityDiscount > 0) {
      return DetailItem(
        label: type == 9 ? '新人优惠' : '活动优惠',
        labelStyle: LabelStyle.labelTitleYellow,
        tagName: '活',
        content: '-￥${controller.activityDiscount.toString()}',
      );
    } else {
      return const SizedBox();
    }
  }

  /// 优惠券
  Widget getCouponPriceStyle() {
    return DetailItem(
        label: '优惠券',
        labelStyle: LabelStyle.labelTitleRed,
        tagName: '券',
        content: controller.showCouponPrice,
        contentStyle: controller.couponList.isNotEmpty ? ContentStyle.nextMore : ContentStyle.normal,
        contentColor: '#e97466',
        onTap: () {
          if (controller.couponList.isNotEmpty) {
            showCouponPopup(
              controller.useCouponIds,
              controller.couponList,
              controller.detail['priceTotal'],
              (couponIds, amount) {
                controller.useCoupon(couponIds!, amount);
              },
              controller.useCouponPrice,
              controller.useCouponIds.length,
            );
          }
        });
  }

  /// 红包
  Widget getRedPackPriceStyle() {
    return DetailItem(
      label: '红包',
      labelStyle: LabelStyle.labelTitleRed,
      tagName: '包',
      content: controller.showRedPackPrice,
      contentStyle: controller.redPackList.isNotEmpty ? ContentStyle.nextMore : ContentStyle.normal,
      contentColor: '#e97466',
      onTap: () {
        if (controller.redPackList.isNotEmpty) {
          showRedPackPopup(
            controller.redPackList,
            controller.detail['priceTotal'],
            (couponIds, amount) {
              controller.useRedPack(couponIds, amount);
            },
            controller.useRedPackPrice,
            controller.useRedPackIds.isEmpty ? 0 : controller.useRedPackIds.length,
            controller.useRedPackIds,
          );
        }
      },
    );
  }

  ///通用容器
  Widget _commonBox(Widget child) {
    return Container(
      margin: EdgeInsets.only(top: 10.h),
      decoration: BoxDecoration(borderRadius: BorderRadius.all(Radius.circular(8.h)), color: Colors.white),
      child: child,
    );
  }

  ///推荐购买
  Widget _recommendTitle() {
    return Padding(
      padding: EdgeInsets.only(top: 11.h),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: [
          Text(
            '顺手买一件',
            style: setTextStyle(12, FontWeight.w400, ThemeConfig.mainTextColor),
          ),
          Row(
            mainAxisAlignment: MainAxisAlignment.end,
            children: [
              Text(
                '换一换',
                style: setTextStyle(12, FontWeight.w500, ThemeConfig.sectionTextColor),
              ),
              Padding(
                padding: EdgeInsets.only(right: 12.w),
                child: Icon(Icons.refresh),
              )
            ],
          )
        ],
      ),
    );
  }

  ///操作按钮组
  Widget _operateBox(BuildContext context) {
    var bottomHeight = MediaQuery.of(context).padding.bottom;
    return Positioned(
        key: GlobalKey(debugLabel: 'Positioned'),
        left: 0,
        bottom: 0,
        child: Container(
          width: 375.w,
          padding: EdgeInsets.only(top: 10.h, bottom: bottomHeight > 0 ? bottomHeight : 10.h),
          color: Colors.white,
          child: Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              Row(
                children: [
                  Padding(
                    padding: EdgeInsets.only(left: 18.w),
                    child: Text(
                      '实付款：',
                      style: setTextStyle(12, FontWeight.w400, ThemeConfig.sectionTextColor),
                    ),
                  ),
                  Text(
                    '￥${controller.actualPrice}',
                    style: setTextStyle(12, FontWeight.w700, ThemeConfig.themeColor),
                  ),
                ],
              ),
              Padding(
                padding: EdgeInsets.only(right: 18.w),
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.end,
                  children: [
                    BaseInteractive(
                      childWidget: Container(
                        width: 90.w,
                        // height: 40.h,
                        padding: const EdgeInsets.all(6),
                        alignment: Alignment.center,
                        decoration: BoxDecoration(color: ThemeConfig.themeColor, borderRadius: BorderRadius.all(Radius.circular(20.h))),
                        child: Text(
                          getSubmitBtnText(),
                          style: setTextStyle(14, FontWeight.w500, Colors.white),
                        ),
                      ),
                      onClick: () {
                        controller.placeOrder();
                      },
                    ),
                  ],
                ),
              )
            ],
          ),
        ));
  }

  ///获取提交订单按钮文本
  String getSubmitBtnText() {
    switch (controller.detail['presaleType']) {
      case 2:
        return '支付定金';
      case null:
      default:
        return '提交订单';
    }
  }

  Widget depositWidget() {
    return Container(
      padding: const EdgeInsets.all(10),
      height: 82.h,
      decoration: const BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.all(Radius.circular(8)),
      ),
      child: Row(
        children: [
          Column(
            mainAxisAlignment: MainAxisAlignment.center,
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Row(
                mainAxisAlignment: MainAxisAlignment.start,
                children: [
                  Text('同意支付定金', style: TextStyle(color: Tools.fromHex('#3D3D3D'), fontSize: 14, fontWeight: FontWeight.w500)),
                  const SizedBox(width: 5),
                  InkWell(
                    onTap: () {
                      Get.toNamed(Routes.statement, arguments: RichTextLinkType.presalePolicy);
                    },
                    child: Container(
                      width: 15,
                      height: 15,
                      decoration: BoxDecoration(
                        shape: BoxShape.circle,
                        border: Border.all(
                          color: Tools.fromHex('#3D3D3D'),
                          width: 1,
                        ),
                      ),
                      child: Center(
                        child: Text(
                          "?",
                          style: TextStyle(
                            fontSize: 10,
                            fontWeight: FontWeight.w400,
                            color: Tools.fromHex('#3D3D3D'), // 问号的颜色和圈保持一致
                          ),
                        ),
                      ),
                    ),
                  )
                ],
              ),
              const SizedBox(height: 10),
              Text('提醒:预售商品定金不退', style: TextStyle(color: Tools.fromHex('#999999'), fontSize: 10, fontWeight: FontWeight.w400)),
            ],
          ),
          const Spacer(),
          BaseCheckBox(
            value: controller.isDepositAgree,
            onChange: (selected) {
              controller.changeProtocol(selected);
            },
          ),
        ],
      ),
    );
  }
}
